﻿using Service.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Service.CertWorkFlow.Steps
{
    public class CertHandOut : StepBodyAsync
    {
        public object handOutConfig { get; set; }
        public override async Task<ExecutionResult> RunAsync(IStepExecutionContext context)
        {
            try
            {
                CertHandOutConfig HandOutConfig= (CertHandOutConfig)handOutConfig;
                var data = context.Workflow.Data as WorkflowData;
                data.Action?.Invoke("正在下发证书");
                //证书分发。
                var handOutInstance = PluginFactory.CreateCertHandOutInstance().FirstOrDefault(s => s.Identity == HandOutConfig.PluginIdentity);
                if (data.CertResult == null)
                {
                    data.Action?.Invoke("证书未获取成功!");
                    throw new Exception("证书未获取成功");
                }
                if (handOutInstance != null)
                {
                    handOutInstance.Config = HandOutConfig.Config;
                    await Task.Run(() =>
                    {
                        var res = handOutInstance.SaveCert(new PluginForCertHandOut.CertFile()
                        {
                            Key = data.CertResult.Key,
                            Pem = data.CertResult.Pem,
                            PFX = data.CertResult.Pfx,
                            PFXPassword = data.CertResult.PfxPassword
                        });
                        data.Action?.Invoke(res.Message);
                    });
                }
                else
                {
                    data.Action?.Invoke($"未找到{HandOutConfig.PluginIdentity}的证书分发插件");
                }
                return ExecutionResult.Next();
            }
            catch (Exception ex)
            {
                var data = context.Workflow.Data as WorkflowData;
                if (data!=null)
                {
                    data.Action?.Invoke($"发生异常{ex.Message}");
                }
                return ExecutionResult.Next();
            }
        }
    }
}
